<template>
    <div class="wh-100% overflow-scroll">
        <n-grid
            class="w-100%"
            responsive="screen"
            cols="m:1 l:2"
            :x-gap="10"
            :y-gap="10"
        >
            <!-- 客户注册申请列表 -->
            <n-gi class="max-h-500px flex flex-col gap-10px">
                <div
                    class="box-border p-10px flex justify-between"
                    style="border-bottom: solid 1px #e5e5e5"
                >
                    <span class="font-bold font-size-20px">待审批</span>
                    <n-button-group>
                        <n-button
                            ghost
                            :focusable="false"
                            @click="sortApprovals('un')"
                        >
                            <n-icon :component="SwapVertical" :size="18" />
                        </n-button>
                        <n-button
                            ghost
                            :focusable="false"
                            @click="refreshApprovals(1)"
                        >
                            <n-icon :component="Refresh" :size="18" />
                        </n-button>
                    </n-button-group>
                </div>
                <div
                    v-if="unfinishedApprovals.length === 0"
                    class="wh-100% flex-center"
                >
                    <n-result
                        status="418"
                        title="暂无申请"
                        description="偷得浮生半日闲，去看看别的吧"
                    >
                    </n-result>
                </div>
                <n-infinite-scroll
                    v-else
                    :distance="40"
                    @load="handleLoadMore(1)"
                >
                    <un-approval-item
                        v-for="item in unfinishedApprovals"
                        :key="item.id"
                        :item="item"
                        @audit:success="handleAudit"
                        @audit:fail="handleAudit"
                        class="mt-16px"
                    />
                    <div
                        v-if="load.unComplete"
                        class="wh-100% flex-center p-10px"
                    >
                        没有更多了
                    </div>
                    <div
                        v-else-if="load.unLoading"
                        class="wh-100% flex-center p-10px"
                    >
                        加载中...
                    </div>
                </n-infinite-scroll>
            </n-gi>
            <!-- 客户注册申请历史记录 -->
            <n-gi class="min-h-300px max-h-500px flex flex-col gap-10px">
                <div
                    class="box-border p-10px flex justify-between"
                    style="border-bottom: solid 1px #e5e5e5"
                >
                    <span class="font-bold font-size-20px">历史记录</span>
                    <n-button-group>
                        <n-button
                            ghost
                            :focusable="false"
                            @click="sortApprovals('fin')"
                        >
                            <n-icon :component="SwapVertical" :size="18" />
                        </n-button>
                        <n-button
                            ghost
                            :focusable="false"
                            @click="refreshApprovals(0)"
                        >
                            <n-icon :component="Refresh" :size="18" />
                        </n-button>
                    </n-button-group>
                </div>
                <div
                    v-if="finishedApprovals.length === 0"
                    class="wh-100% flex-center"
                >
                    <n-result
                        status="418"
                        title="暂无记录"
                        description="舍去过往是为了更好的将来"
                    >
                    </n-result>
                </div>
                <n-infinite-scroll
                    v-else
                    :distance="40"
                    @load="handleLoadMore(0)"
                >
                    <fin-approval-item
                        v-for="item in finishedApprovals"
                        :key="item.id"
                        :item="item"
                        class="mt-16px"
                    />
                    <div
                        v-if="load.finComplete"
                        class="wh-100% flex-center p-10px"
                    >
                        没有更多了
                    </div>
                    <div
                        v-else-if="load.finLoading"
                        class="wh-100% flex-center p-10px"
                    >
                        加载中...
                    </div>
                </n-infinite-scroll>
            </n-gi>
        </n-grid>
    </div>
</template>

<script lang="ts" setup>
import { ref, onMounted } from "vue";

import {
    getApprovals,
    auditCustomerApproval,
} from "@/service/api/modules/customer";

import { SwapVertical, Refresh } from "@vicons/ionicons5";

import type { CustomerApproval } from "@/service/api/types/user";
import UnApprovalItem from "../components/un-approval-item/index.vue";
import FinApprovalItem from "../components/fin-approval-item/index.vue";

// 缓存的客户注册申请
const unfinishedApprovals = ref<CustomerApproval[]>([]);
// 缓存的客户注册申请历史记录
const finishedApprovals = ref<CustomerApproval[]>([]);

// 客户注册申请按日期的排序次序
const unSortOrder = ref<"asc" | "desc">("desc");
// 客户注册申请历史记录按日期的排序次序
const finSortOrder = ref<"asc" | "desc">("desc");

const load = ref({
    unLoading: false,
    unComplete: false,
    finLoading: false,
    finComplete: false,
});

const unfinishedPagination = {
    page: 1,
    size: 10,
};

// 已完成注册申请历史记录分页
const finishedPagination = {
    page: 1,
    size: 10,
};

// 获取客户注册申请接口
const getApprvals = async (model: 0 | 1) => {
    try {
        model === 0
            ? (load.value.unLoading = true)
            : (load.value.finLoading = true);
        return await getApprovals(
            {
                page:
                    model === 0
                        ? finishedPagination.page
                        : unfinishedPagination.page,
                size:
                    model === 0
                        ? finishedPagination.size
                        : unfinishedPagination.size,
            },
            model
        );
    } catch (err) {
        window.NMessage.error((err as Error).message);
        return [];
    } finally {
        model === 0
            ? (load.value.unLoading = false)
            : (load.value.finLoading = false);
    }
};

// 判断是否加载完成 -> 如果加载出来的条数小于分页大小，说明加载完成
const isComplete = (type: 0 | 1) => {
    if (type === 0) {
        return (
            finishedApprovals.value.length <
            finishedPagination.page * finishedPagination.size
        );
    } else {
        return (
            unfinishedApprovals.value.length <
            unfinishedPagination.page * unfinishedPagination.size
        );
    }
};

onMounted(async () => {
    try {
        finishedApprovals.value = await getApprvals(0);
        unfinishedApprovals.value = await getApprvals(1);
        load.value.finComplete = isComplete(0);
        load.value.unComplete = isComplete(1);
        unfinishedPagination.page += 1;
        finishedPagination.page += 1;
    } catch (err) {
        window.NMessage.error((err as Error).message);
    }
});

// 刷新客户注册申请列表
const refreshApprovals = (type: 0 | 1) => {
    if (type === 0) {
        load.value.finComplete = false;
        load.value.finLoading = false;
        finishedPagination.page = 1;
        finishedApprovals.value = [];
        handleLoadMore(0);
    } else {
        load.value.unComplete = false;
        load.value.unLoading = false;
        unfinishedPagination.page = 1;
        unfinishedApprovals.value = [];
        handleLoadMore(1);
    }
};

const handleLoadMore = async (type: 0 | 1) => {
    if (type === 0 ? load.value.finComplete : load.value.unComplete) {
        return;
    }
    try {
        const res = await getApprvals(type);
        if (res.length === 0) {
            load.value[type === 0 ? "finLoading" : "unLoading"] = false;
        }
        if (type === 0) {
            finishedApprovals.value.push(...res);
            load.value.finComplete = isComplete(0);
            finishedPagination.page += 1;
        } else {
            unfinishedApprovals.value.push(...res);
            load.value.unComplete = isComplete(1);
            unfinishedPagination.page += 1;
        }
    } catch (err) {
        window.NMessage.error((err as Error).message);
    }
};

const sortApprovals = (type: "un" | "fin") => {
    if (type === "un") {
        if (unSortOrder.value === "asc") {
            unfinishedApprovals.value.sort(
                (a, b) => a.createdTime - b.createdTime
            );
            unSortOrder.value = "desc";
        } else {
            unfinishedApprovals.value.sort(
                (a, b) => b.createdTime - a.createdTime
            );
            unSortOrder.value = "asc";
        }
    } else {
        if (finSortOrder.value === "asc") {
            finishedApprovals.value.sort(
                (a, b) => a.createdTime - b.createdTime
            );
            finSortOrder.value = "desc";
        } else {
            finishedApprovals.value.sort(
                (a, b) => b.createdTime - a.createdTime
            );
            finSortOrder.value = "asc";
        }
    }
};

const handleAudit = async (id: string, comment?: string) => {
    try {
        comment
            ? await auditCustomerApproval({
                  id: id,
                  status: 0,
                  comments: comment,
              })
            : await auditCustomerApproval({
                  id: id,
                  status: 1,
              });
        window.NMessage.success("操作成功");
        refreshApprovals(0);
        refreshApprovals(1);
    } catch (err) {
        window.NMessage.error((err as Error).message);
    }
};
</script>

<style scoped></style>
